//
//  SiSaveVC.swift
//  SiliUtility
//
//  Created by Li Dong on 2023/10/17.
//

import UIKit

class SiSaveVC: SiBaseVC {
    
    
    @IBOutlet weak var startTF: UITextField!
    @IBOutlet weak var addTF: UITextField!
    @IBOutlet weak var totalTF: UITextField!
    @IBOutlet weak var startDateTF: UITextField!
    
    var startDate: Date?
    var totalAmount: Double = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        title = "365存钱"
        startTF.delegate = self
        addTF.delegate = self
    }
    
    lazy var df: DateFormatter = {
        let temp = DateFormatter()
        temp.dateFormat = "yyyy.MM.dd"
        return temp
    }()

    @IBAction func selectDateHandler(_ sender: Any) {
        view.endEditing(true)
        let pickerVC = SiDatePickerVC()
        pickerVC.callBack = {[weak self] date in
            guard let self = self else { return  }
            self.startDate = date
            self.startDateTF.text = df.string(from: date)
        }
        pickerVC.modalPresentationStyle = .overCurrentContext
        present(pickerVC, animated: true)
    }
    
    @IBAction func startSave(_ sender: Any) {
        if (startTF.text?.isEmpty ?? true) || (addTF.text?.isEmpty ?? true) || (startDateTF.text?.isEmpty ?? true) {
            showHUDTextOnly("请输入内容")
            return
        }
        guard let startStr = startTF.text else { return  }
        if !startStr.isValiteNumber() || (Double(startStr) ?? 0) > 1000 ||  (Double(startStr) ?? 0) < 1 {
            showHUDTextOnly("请输入1~1000的数值")
            return
        }
        guard let addStr = addTF.text else { return  }
        if !addStr.isValiteNumber() || (Double(addStr) ?? 0) > 1000 ||  (Double(addStr) ?? 0) < 1 {
            showHUDTextOnly("请输入1~1000的数值")
            return
        }
        navigationController?.pushViewController(SiSaveDetailVC(startDate: startDate, startAmount: (Double(startStr) ?? 0), addNumber: (Double(addStr) ?? 0), totalAmount: totalAmount), animated: true)
    }
    

}

extension SiSaveVC: UITextFieldDelegate {
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        guard let startStr = startTF.text else { return true }
        if !startStr.isValiteNumber()  {
            return true
        }
        guard let addStr = addTF.text else { return  true}
        if !addStr.isValiteNumber(){
            return true
        }
        //计算预计总金额S = n/2 × (2a + (n-1) × d)
        totalAmount = (365/2) * (2*Double(startStr)! + 364*Double(addStr)!)
        totalTF.text = String(format: "￥%.2f", totalAmount)
        print("total = ", totalTF.text!)
        if totalTF.text!.hasSuffix(".00") {
            totalTF.text = totalTF.text!.replacingOccurrences(of: ".00", with: "")
        }
        if totalTF.text!.hasSuffix(".0") {
            totalTF.text = totalTF.text!.replacingOccurrences(of: ".0", with: "")
        }
        return true
    }
}
